import { LogicEntity } from "./LogicEntity";
import { ObjHandle } from "../Framework/ObjHandle";
import { IGame } from "./Game/IGame";
import { MsgDispatcher } from "../Framework/Network/MsgDispatcher";
import { L2VMessageEnum } from "../Framework/Network/L2VMessageEnum";
import { LogicTileEntity } from "./LogicTileEntity";

export class GameManager {

    static nextEntityID = 0;

    game: IGame;

    allEntitiesMap: {[key:number]:ObjHandle<LogicEntity>} = {}

    constructor(game: IGame)
    {
        this.game = game;
    }

    tick(dt, operation)
    {
        
        if(this.game != null)
        {
            this.game.tick(dt, operation);
        }
    }

    createEntity(characterID: number): number
    {
        let entityID: number = GameManager.nextEntityID++;
        MsgDispatcher.getInstance().dispatchMsg(L2VMessageEnum.CreateEntity, [entityID, characterID]);
        

        let entity = new LogicTileEntity();
        let entityHandler = new ObjHandle<LogicEntity>(entity);
        this.allEntitiesMap[entityID] = entityHandler;
        entity.characterID = characterID;
        entity.entityID = entityID;
        entity.init()
        

        return entityID;
    }

    delEntity(entityID: number):void
    {
        MsgDispatcher.getInstance().dispatchMsg(L2VMessageEnum.DelEntity, [entityID]);

        let entity = this.allEntitiesMap[entityID];
        if(entity != undefined && entity != null)
        {
            entity.instance.destroy();
            entity.release();
        }

        this.allEntitiesMap[entityID] = null;
    }

    getEntity(entityID: number): ObjHandle<LogicEntity>
    {
        let entity = this.allEntitiesMap[entityID];
        if(entity == undefined)
        {
            return ObjHandle.NULL;
        }
        else
        {
            return entity;
        }
    }

    destroy(): void
    {
        for(let key in this.allEntitiesMap)
        {
            this.allEntitiesMap[key].instance.destroy();
            this.allEntitiesMap[key].release();
        }

        this.allEntitiesMap = null;
    }
}
